<?php

namespace components\orm;

use \components\orm\dbclass as dbclass;

class orm {

    public $conn;
    protected $config;
    protected $query;
    protected $table;
    public $fResult = array();
    public function __construct($config) {
        $this->config = $config;  
    }
    public function getConn(){
        switch ($this->config['driver']) {
            case "mongodb":
                $this->conn = new dbclass\mongo($this->config);
                break;
            default:
                $this->conn = new dbclass\sqldb($this->config);
                break;
        }
    }
    public function setTable($table){
        $this->table = $table;
        return $this;
    }

    public function create($record) {
        $this->conn->prepare($record);
        return $this;
    }

    public function add() {
        $this->conn->create($this->table);
        return $this;
    }

    public function find() {
        $result = $this->conn->readOne($this->table);
        return $result;
    }

    public function findAll() {
        $result = $this->conn->read($this->table);
        $arr = array();
        for($i=0;$i<count($result);$i++){
            foreach ($result[$i] as $key => $value){
                if(is_string($key)){
                    $arr[$i][$key] = $value;
                }
            }
        }
        return $arr;
    }
    public function update() {
        $this->conn->update($this->table);
        return $this;
    }

    public function delete() {
        $this->conn->delete($this->table);
        return $this;
    }

    public function query($query = null) {
        $this->conn->setCondition($query);
        return $this;
    }

    public function field($field = null) {
        $this->conn->setColumn($field);
        return $this;
    }
    public function limit($limit = null){
        if(isset($limit[0]) && is_int($limit[0])){
            $start = $limit[0];
        }else{
            $start = "";
        }
        if(isset($limit[1]) && is_int($limit[1])){
            $stop = $limit[1];
        }else{
            $stop = "";
        }
        $this->conn->setLimit($start,$stop);
        return $this;
    }

    public function order($order = null){
        if(isset($order[0]) && isset($order[1])){
            $this->conn->setOrder($order[0],$order[1]); 
        }
        return $this;
    }

}

?>
